﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpticalPowerMeter.UserControls;

namespace OpticalPowerMeter
{
    /// <summary>
    /// SerialGroupWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SerialGroupWindow : Window
    {
        public SerialGroupWindow()
        {
            InitializeComponent();
            InitSerialPorts();//添加串口控件
            InitSerialGroupList(); //初始化串口组清单
        }

        //添加串口控件
        private void InitSerialPorts()
        {
            for(int i = 0; i < 7; i++)
            {
                SerialPortControl serialPortControl = new SerialPortControl();
                SerialPortsGroup.Children.Add(serialPortControl);
                Grid.SetRow(serialPortControl,i + 2);
                serialPortControl.HorizontalAlignment = HorizontalAlignment.Center;
                serialPortControl.VerticalAlignment = VerticalAlignment.Center;
            }
        }


        #region 绑定显示的属性
        //机型清单表头字号
        static DependencyProperty DataGridHeadFontProperty = DependencyProperty.Register(
            "DataGridHeadFont",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //单元字号
        static DependencyProperty CellFontProperty = DependencyProperty.Register(
            "CellFont",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //单元高度
        static DependencyProperty CellHeightProperty = DependencyProperty.Register(
            "CellHeight",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //数据列宽
        static DependencyProperty DataGridColumnWidthProperty = DependencyProperty.Register(
            "DataGridColumnWidth",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //串口组名字号
        static DependencyProperty GroupNameSizeProperty = DependencyProperty.Register(
            "GroupNameSize",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //串口组名边距
        static DependencyProperty GroupNameLabelMarginProperty = DependencyProperty.Register(
            "GroupNameLabelMargin",
            typeof(Thickness),
            typeof(SerialGroupWindow)
            );

        //串口组输入框边距
        static DependencyProperty GroupNameBoxMarginProperty = DependencyProperty.Register(
            "GroupNameBoxMargin",
            typeof(Thickness),
            typeof(SerialGroupWindow)
            );

        //串口组输入框高度
        static DependencyProperty GroupNameBoxHeightProperty = DependencyProperty.Register(
            "GroupNameBoxHeight",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //串口组输入框宽度
        static DependencyProperty GroupNameBoxWidthProperty = DependencyProperty.Register(
            "GroupNameBoxWidth",
            typeof(double),
            typeof(SerialGroupWindow)
            );

        //保存按钮的边距
        static DependencyProperty SaveButtonMarginProperty = DependencyProperty.Register(
            "SaveButtonMargin",
            typeof(Thickness),
            typeof(SerialGroupWindow)
            );

        //删除按钮的边距
        static DependencyProperty DeleteButtonMarginProperty = DependencyProperty.Register(
            "DeleteButtonMargin",
            typeof(Thickness),
            typeof(SerialGroupWindow)
            );
        #endregion


        //尺寸发生变化时，调整控件大小及位置
        private void Size_Changed(object sender,SizeChangedEventArgs args) {
            #region 刷新左侧串口组列表字号等内容
            Grid parentGrid = (Grid)SerialGroupDataGrid.Parent;
            double parentWidth = parentGrid.ActualWidth;
            SerialGroupDataGrid.Width = parentWidth;
            double dataGridWidth = parentWidth;
            SetValue(DataGridColumnWidthProperty, dataGridWidth);  //设置列宽
            double height = dataGridWidth / 6;
            double headFontSize = Math.Round((height - 10) / 1.27, 1);  //head字号
            SetValue(DataGridHeadFontProperty, headFontSize);
            SetValue(CellFontProperty, headFontSize - 2); //内容比head小2个字号
            SetValue(CellHeightProperty, Math.Round((headFontSize - 2) * 1.27, 1));
            #endregion
            #region 右侧的字号等内容
            double portsGridHeight = Math.Round(SerialPortsGroup.ActualHeight/9,1);
            double portsGridWidth = SerialPortsGroup.ActualWidth;
            //设置字号
            if (portsGridWidth / portsGridHeight > 20)
            {
                double fontSize = Math.Round((portsGridHeight - 10) / 1.27, 1);
                SetValue(GroupNameSizeProperty, fontSize);
            }
            else
            {
                double fontSize = Math.Round((portsGridWidth - 10) / 20, 1);
                SetValue(GroupNameSizeProperty, fontSize);
            }
            //设置输入尺寸
            double groupnameFontSize = (double)GetValue(GroupNameSizeProperty);
            double groupnameHeight = groupnameFontSize * 1.27;
            double groupnameBoxWidth = groupnameFontSize * 10;
            SetValue(GroupNameBoxHeightProperty, groupnameHeight);
            SetValue(GroupNameBoxWidthProperty, groupnameBoxWidth);
            //设置Label及输入框的边距
            double labelLeft = (portsGridWidth - groupnameFontSize * 14 - 25) / 2;
            SetValue(GroupNameLabelMarginProperty,new Thickness(labelLeft,0,0,0));
            double boxLeft = labelLeft + groupnameFontSize * 4 + 20;
            SetValue(GroupNameBoxMarginProperty,new Thickness(boxLeft,0,0,0));
            //设置串口设置控件尺寸
            double serialPortControlWidth = 0;
            double serialPortControlHeight = 0;
            if (portsGridWidth / portsGridHeight > 14) { //宽度大于高度的14倍，以高度设置控件。否则以宽度设置控件
                serialPortControlHeight = portsGridHeight;
                serialPortControlWidth = serialPortControlHeight * 14;
            }
            else
            {
                serialPortControlWidth = portsGridWidth;
                serialPortControlHeight = serialPortControlWidth / 14;
            }
            if (serialPortControlWidth==0 || serialPortControlHeight==0) {
                return;
            }
            foreach (object obj in SerialPortsGroup.Children) {
                if (obj.GetType().ToString().EndsWith("SerialPortControl")) {
                    SerialPortControl portcontrol = obj as SerialPortControl;
                    portcontrol.Height = serialPortControlHeight;
                    portcontrol.Width = serialPortControlWidth;
                }
            }
            #endregion
            #region 底部按钮边距
            double buttonActualWidth = groupnameFontSize * 2 + 10;
            double saveButtonLeft = portsGridWidth/2-buttonActualWidth-20;
            SetValue(SaveButtonMarginProperty,new Thickness(saveButtonLeft,0,0,0));
            double deleteButtonLeft = saveButtonLeft + buttonActualWidth + 40;
            SetValue(DeleteButtonMarginProperty,new Thickness(deleteButtonLeft,0,0,0));
            #endregion
        }

        //保存配置文件
        private void SaveButton_Click(object sender,RoutedEventArgs args ) {
            string groupName = GroupNameBox.Text.Trim();
            if (groupName == "")
            {
                MessageBox.Show("串口组名为空", "无法添加空串口组", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            List<SerialPortParam> serialPortParams = new List<SerialPortParam>();
            foreach (object obj in SerialPortsGroup.Children)
            {
                if (obj.GetType().ToString().EndsWith("SerialPortControl"))
                {
                    SerialPortControl portcontrol = obj as SerialPortControl;
                    SerialPortParam serialPortParam = new SerialPortParam();
                    string portname = portcontrol.Portname.ToString();
                    int baudrate = Convert.ToInt32(portcontrol.Baudrate);
                    serialPortParam.Portname = portname;
                    serialPortParam.Baudrate = baudrate;
                    serialPortParams.Add(serialPortParam);
                }
            }
            SerialGroupManagement.GetInstance().SaveData(groupName,serialPortParams);
            MessageBox.Show("保存串口组" + groupName + "完成", "保存完成", MessageBoxButton.OK, MessageBoxImage.Information);
            //刷新列表
            InitSerialGroupList();
        }


        //删除串口组
        private void DeleteButton_Click(object sender,RoutedEventArgs args) {
            string groupName = GroupNameBox.Text.Trim();
            if (groupName == "")
            {
                return;
            }
            MessageBoxResult clickButton = MessageBox.Show("是否确定要删除" + groupName, "删除串口组", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (clickButton == MessageBoxResult.Yes)
            {
                SerialGroupManagement.GetInstance().DeleteGroup(groupName);
            }
            //刷新列表
            InitSerialGroupList();
        }

        //读取串口组清单，显示在列表中
        private void InitSerialGroupList()
        {
            List<string> serialGroupList = SerialGroupManagement.GetInstance().GetPortGroupNameList();
            SerialGroupDataGrid.ItemsSource = null;
            SerialGroupDataGrid.ItemsSource = serialGroupList;
        }

        //选中串口组名时，右侧刷新名称及对应的串口信息
        private void SerialGroupDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            string groupName = SerialGroupDataGrid?.SelectedValue?.ToString().Trim();
            if (groupName == null || groupName == "")
            {
                return;
            }
            #region 获取选中的组名，并将其参数显示在右侧
            List<SerialPortParam> serialPortParams = SerialGroupManagement.GetInstance().GetPortParamList(groupName);
            List<SerialPortControl> serialPortControls = GetSerialPortControls();
            GroupNameBox.Text = groupName;
            for (int i = 0 ; i < serialPortParams.Count ; i++) {
                serialPortControls[i].Portname = serialPortParams[i].Portname;
                serialPortControls[i].Baudrate = serialPortParams[i].Baudrate.ToString();
            }
            #endregion
        }

        //获取串口配置清单
        private List<SerialPortControl> GetSerialPortControls()
        {
            List<SerialPortControl> serialPortControls = new List<SerialPortControl>();
            foreach (object obj in SerialPortsGroup.Children)
            {
                if (obj.GetType().ToString().EndsWith("SerialPortControl"))
                {
                    SerialPortControl portcontrol = obj as SerialPortControl;
                    serialPortControls.Add(portcontrol);
                }
            }
            return serialPortControls;
        }
    }
}
